package com.softeem.ossmusic.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.softeem.ossmusic.comm.R;
import com.softeem.ossmusic.entity.User;
import com.softeem.ossmusic.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Tag(name = "用户管理")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Operation(summary = "用户列表",description = "根据提供的页码和数据条数实现分页查询")
    @Parameters({
            @Parameter(name = "page",description = "页码"),
            @Parameter(name = "limit",description = "数据条数")
    })
    @GetMapping("/user/list")
    public R list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit){
        //创建分页对象
        IPage<User> ipage = new Page<>(page, limit);
        //执行查询(分页)
        userService.page(ipage);
        //返回结果
        return R.success().setData(ipage.getRecords()).setCount(ipage.getTotal());
    }

    @Operation(summary = "用户登录",description = "根据用户名和密码实现登录")
    @Parameters({
            @Parameter(name = "username",description = "用户名"),
            @Parameter(name = "password",description = "密码")
    })
    @GetMapping("/user/login")
    public R login(String username,String password){
        return userService.login(username,password);
    }

    @Operation(summary = "用户注册",description = "根据用户名和密码实现注册")
    @PostMapping("/user/reg")
    public R register(@RequestBody User user){
        //设置默认注册时间和状态
        if(user.getCreateTime() == null){
            user.setCreateTime(new Date());
        }
        if(user.getStatus() == null){
            user.setStatus(1); // 1表示启用，0表示禁用
        }
        return userService.register(user);
    }
    
    @Operation(summary = "用户详情", description = "根据id查询用户详情")
    @GetMapping("/user/details")
    public R details(Integer id){
        User user = userService.getById(id);
        if(user == null){
            return R.error().setMsg("用户不存在");
        }
        //隐藏密码信息
        user.setPassword(null);
        return R.success().setData(user);
    }
    
    @Operation(summary = "修改用户信息", description = "根据id修改用户信息")
    @PutMapping("/user/update")
    public R update(@RequestBody User user){
        if(user.getId() == null || userService.getById(user.getId()) == null){
            return R.error().setMsg("用户不存在");
        }
        //保留原密码，不允许直接修改密码
        User old = userService.getById(user.getId());
        user.setPassword(old.getPassword());
        
        if(userService.updateById(user)){
            return R.success().setMsg("修改成功");
        }
        return R.error().setMsg("修改失败");
    }
    
    @Operation(summary = "修改密码", description = "修改用户密码")
    @PostMapping("/user/updatePassword")
    public R updatePassword(@RequestBody User user){
        if(user.getId() == null || userService.getById(user.getId()) == null){
            return R.error().setMsg("用户不存在");
        }
        if(user.getPassword() == null || user.getPassword().trim().isEmpty()){
            return R.error().setMsg("密码不能为空");
        }
        
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setPassword(user.getPassword());
        
        if(userService.updateById(updateUser)){
            return R.success().setMsg("密码修改成功");
        }
        return R.error().setMsg("密码修改失败");
    }
    
    @Operation(summary = "禁用/启用用户", description = "根据id禁用或启用用户")
    @PutMapping("/user/setStatus")
    public R setStatus(Integer id, Integer status){
        if(id == null || userService.getById(id) == null){
            return R.error().setMsg("用户不存在");
        }
        if(status == null || (status != 0 && status != 1)){
            return R.error().setMsg("状态值无效，必须为0(禁用)或1(启用)");
        }
        
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        
        if(userService.updateById(user)){
            return R.success().setMsg("状态更新成功");
        }
        return R.error().setMsg("状态更新失败");
    }
    
    @Operation(summary = "删除用户", description = "根据id删除用户")
    @DeleteMapping("/user/delete")
    public R delete(Integer id){
        if(id == null || userService.getById(id) == null){
            return R.error().setMsg("用户不存在");
        }
        
        if(userService.removeById(id)){
            return R.success().setMsg("删除成功");
        }
        return R.error().setMsg("删除失败");
    }
    
    @Operation(summary = "黑名单列表", description = "获取黑名单中的用户（状态为禁用的用户）")
    @Parameters({
            @Parameter(name = "page",description = "页码"),
            @Parameter(name = "limit",description = "数据条数")
    })
    @GetMapping("/user/blacklist")
    public R blacklist(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit){
        //创建分页对象
        IPage<User> ipage = new Page<>(page, limit);
        //执行查询(分页)，只查询状态为禁用（1）的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 假设1表示禁用状态
        userService.page(ipage, queryWrapper);
        //隐藏密码信息
        ipage.getRecords().forEach(user -> user.setPassword(null));
        //返回结果
        return R.success().setData(ipage.getRecords()).setCount(ipage.getTotal());
    }
    
    @Operation(summary = "搜索用户", description = "根据用户名或昵称搜索用户")
    @GetMapping("/user/search")
    public R search(String keyword){
        if(keyword == null || keyword.trim().isEmpty()){
            return R.error().setMsg("搜索关键词不能为空");
        }
        
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", keyword).or().like("nickname", keyword);
        
        List<User> list = userService.list(queryWrapper);
        //隐藏密码
        list.forEach(u -> u.setPassword(null));
        
        return R.success().setData(list);
    }
}
